package com.eastfair.certificate.controller;

import com.eastfair.annotation.annotation.base.BaseControllerInfo;
import com.eastfair.certificate.dto.*;
import com.eastfair.certificate.entity.FormField;
import com.eastfair.certificate.entity.FormFieldSubsystem;
import com.eastfair.certificate.enumeration.FormFieldSubsystemFieldTypeAttributeEnum;
import com.eastfair.certificate.enumeration.FormFieldSubsystemMethodTypeEnum;
import com.eastfair.certificate.service.FormFieldService;
import com.eastfair.certificate.service.FormFieldSubsystemService;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.eastfair.boot.controller.SuperController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.certificate.vo.FormFieldSubsystemVO;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.echo.core.EchoService;
import com.eastfair.core.base.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.eastfair.annotation.annotation.security.PreAuth;

import com.eastfair.boot.request.PageParams;
import com.eastfair.core.context.ContextUtil;


/**
 * <p>
 * 前端控制器
 * 动态表单
 * </p>
 *
 * @author ligang
 * @date 2023-05-17
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/formFieldSubsystem")
@Api(value = "FormFieldSubsystem", tags = "动态表单")
@PreAuth(replace = "certificate:formFieldSubsystem:")
public class FormFieldSubsystemController extends SuperController<FormFieldSubsystemService, Long, FormFieldSubsystem, FormFieldSubsystemPageQuery, FormFieldSubsystemSaveDTO, FormFieldSubsystemUpdateDTO> {

    @Autowired
    private EchoService echoService;

    @Autowired
    private FormFieldService formFieldService;



    @Override
    public void handlerResult(IPage<FormFieldSubsystem> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<FormFieldSubsystem> formFieldSubsystemList = list.stream().map((map) -> {
            FormFieldSubsystem formFieldSubsystem = FormFieldSubsystem.builder().build();
            //TODO 请在这里完成转换
            return formFieldSubsystem;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(formFieldSubsystemList));
    }



    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<FormFieldSubsystemPageQuery> params) {
        FormFieldSubsystemPageQuery pageQuery = params.getModel();

    }


    /**
     * 复制表单
     *
     * @param formFieldSubsystemDTO
     * @return 是否成功
     */
    @ApiOperation(value = "复制表单", notes = "复制表单")
    @PostMapping("/copyFormField")
    public R<Boolean> copyFormFieldList(@RequestBody FormFieldSubsystemDTO formFieldSubsystemDTO) {
        FormFieldDTO queryFormField = new FormFieldDTO();
        queryFormField.setGroupId(formFieldSubsystemDTO.getGroupId());
        List<FormField> formFieldList = formFieldService.list(queryFormField, null);
        if (formFieldList != null && !formFieldList.isEmpty()) {
            for (FormField formField : formFieldList) {
                FormFieldSubsystem formFieldSubsystem = new FormFieldSubsystem();
                BeanUtils.copyProperties(formField, formFieldSubsystem, "id");
                formFieldSubsystem.setRelatedId(formFieldSubsystemDTO.getRelatedId());
                if (formField.getFieldTypeAttribute() != null) {
                    formFieldSubsystem.setFieldTypeAttribute(FormFieldSubsystemFieldTypeAttributeEnum.get(formField.getFieldTypeAttribute().getCode()));
                }
                if (formField.getMethodType() != null) {
                    formFieldSubsystem.setMethodType(FormFieldSubsystemMethodTypeEnum.get(formField.getMethodType().getCode()));
                }
                baseService.save(formFieldSubsystem);
            }
        }
        return R.success(Boolean.TRUE);
    }


    /**
     * 修改表单配置
     *
     * @param formFieldSubsystemDTO 表单实体
     * @return 是否成功
     */
    @ApiOperation(value = "修改表单配置", notes = "修改表单配置")
    @PutMapping("/updateFormFieldSubsystem")
    public R<Boolean> updateFormFieldSubsystem(@RequestBody FormFieldSubsystemDTO formFieldSubsystemDTO) {
        return baseService.updateFormField(formFieldSubsystemDTO);
    }

    /**
     * 删除表单配置
     *
     * @param id 主键
     * @return 是否成功
     */
    @ApiOperation(value = "删除表单配置", notes = "删除表单配置")
    @DeleteMapping("/{id}")
    public R<Boolean> deleteById(@PathVariable("id") Long id) {
        return R.success(baseService.updateById(FormFieldSubsystem.builder().id(id).isDeleted(BusinessConstant.DELETE_YES).build()));
    }

    /**
     * 根据表单类型获取表单
     *
     * @param formFieldSubsystemDTO 表单过滤条件
     * @return 表单列表
     */
    @ApiOperation(value = "根据表单类型获取表单", notes = "根据表单类型获取表单")
    @PostMapping("/list")
    @BaseControllerInfo()
    public R<List<FormFieldSubsystemVO>> list(@RequestBody FormFieldSubsystemDTO formFieldSubsystemDTO) {
        return R.success(baseService.doToVos(baseService.list(formFieldSubsystemDTO, null)));
    }


    /**
     * 置顶
     *
     * @param id 主键id
     * @return 表单列表
     */
    @ApiOperation(value = "置顶", notes = "置顶")
    @GetMapping("/top")
    public R top(Long id) {
        int num = 1;
        FormFieldSubsystem formFieldSubsystem = baseService.getByIdCache(id);
        if (formFieldSubsystem == null) {
            return R.success();
        }
        formFieldSubsystem.setSequence(num++);
        baseService.updateById(formFieldSubsystem);
        //其他重新排序
        FormFieldSubsystemDTO queryFormField = new FormFieldSubsystemDTO();
        queryFormField.setGroupId(formFieldSubsystem.getGroupId());
        List<FormFieldSubsystem> formFieldSubsystemList = baseService.list(queryFormField, null);
        if (formFieldSubsystemList != null && !formFieldSubsystemList.isEmpty()) {
            for (FormFieldSubsystem fieldSubsystem : formFieldSubsystemList) {
                if (!fieldSubsystem.getId().equals(formFieldSubsystem.getId())) {
                    fieldSubsystem.setSequence(num++);
                    baseService.updateById(fieldSubsystem);
                }
            }
        }
        return R.success();
    }


    /**
     * 查询动态表单列表给业务系统
     *
     * @param formFieldSubsystemDTO 表单过滤条件
     * @return 表单列表
     */
    @ApiOperation(value = "查询动态表单列表给业务系统", notes = "查询动态表单列表给业务系统")
    @PostMapping("/listDynamicFrom")
    @BaseControllerInfo()
    public R<List<FormFieldSubsystemVO>> listDynamicFrom(@RequestBody FormFieldSubsystemDTO formFieldSubsystemDTO) {
        List<FormFieldSubsystemVO> formFieldSubsystemList = baseService.doToVos(baseService.list(formFieldSubsystemDTO, null));
        if (formFieldSubsystemList == null || formFieldSubsystemList.isEmpty()) {
            return R.success(null);
        }
        return R.success(formFieldSubsystemList);
    }

    /**
     * 校验动态表单
     *
     * @param formFieldSubsystemVOList
     * @return 是否成功
     */
    @ApiOperation(value = "校验动态表单", notes = "校验动态表单")
    @PostMapping("/verifyForm")
    public R submitForm(@RequestBody List<FormFieldSubsystemVO> formFieldSubsystemVOList) {
        List<Long> ids = formFieldSubsystemVOList.stream().filter(s -> s.getId() != null).map(FormFieldSubsystemVO::getId).collect(Collectors.toList());
        List<FormFieldSubsystemVO> formFieldSubsystemVOList1 = baseService.doToVos(baseService.list(null, ids));
        for (FormFieldSubsystemVO formFieldSubsystemVO : formFieldSubsystemVOList1) {
            for (FormFieldSubsystemVO formFieldSubsystemVO1 : formFieldSubsystemVOList) {
                if (formFieldSubsystemVO1.getId() != null && formFieldSubsystemVO1.getId().equals(formFieldSubsystemVO.getId())) {
                    formFieldSubsystemVO.setValue(formFieldSubsystemVO1.getValue());
                }
            }

        }
        R<String> r = baseService.checkFormFieldInfo(formFieldSubsystemVOList1);
        if ((!r.getIsSuccess()) || (r.getData() != null && r.getData().length() > 0)) {
            return r;
        }
//        R<Test1DynamicForm> test1DynamicFormR = convertByFormField.assembleFieldToObject(formFieldParamList, Test1DynamicForm.class);
//        return test1DynamicFormR;
        return R.success();
    }

    /**
     * 查询提交后的表单填写信息
     *
     * @param map 表单组id
     * @return
     */
    @ApiOperation(value = "查询提交后的表单填写信息", notes = "查询提交后的表单填写信息")
    @PostMapping("/findsubmitForm")
    public R findsubmitForm(@RequestBody Map<String, Object> map) {
        Long relatedId = Long.parseLong(map.get("relatedId").toString());
        Object object = map.get("object");
        FormFieldSubsystemDTO formFieldSubsystemDTO = new FormFieldSubsystemDTO();
        formFieldSubsystemDTO.setRelatedId(relatedId);
        formFieldSubsystemDTO.setIsEnabled(BusinessConstant.YES);
        List<FormFieldSubsystemVO> formFieldSubsystemVOList = baseService.doToVos(baseService.list(formFieldSubsystemDTO, null));
//        R<List<FormFieldDynamicFrom>> r = ConvertByFormField.assembleObjectToField(formFieldSubsystemVOList, object);
        return R.success();
    }


    /**
     * 同步业务表单
     *
     * @param formFieldSubsystemDTO 表单
     * @return
     */
    @ApiOperation(value = "同步业务表单", notes = "同步业务表单")
    @PostMapping("/sycnsubmitForm")
    public R sycnsubmitForm(@RequestBody FormFieldSubsystemDTO formFieldSubsystemDTO) {
        FormFieldSubsystemDTO queryFormFieldSubsystemDTO = new FormFieldSubsystemDTO();
        queryFormFieldSubsystemDTO.setRelatedId(formFieldSubsystemDTO.getRelatedId());
        List<FormFieldSubsystem> formFieldSubsystemList = baseService.list(queryFormFieldSubsystemDTO, null);
        if (formFieldSubsystemList == null || formFieldSubsystemList.isEmpty()) {
            return R.success();
        }
        FormFieldDTO formFieldDTO = new FormFieldDTO();
        formFieldDTO.setGroupId(formFieldSubsystemList.get(0).getGroupId());
        List<FormField> formFieldList = formFieldService.list(formFieldDTO, null);
        if (formFieldList == null || formFieldList.isEmpty()) {
            return R.success();
        }
        for (FormField formField1 : formFieldList) {
            boolean pan = true;
            for (FormFieldSubsystem formFieldSubsystem : formFieldSubsystemList) {
                if (formField1.getKeyword().equals(formFieldSubsystem.getKeyword())) {
                    pan = false;
                }
            }
            if (pan) {
                FormFieldSubsystem saveFormFieldSubsystem = new FormFieldSubsystem();
                BeanUtils.copyProperties(formField1, saveFormFieldSubsystem, "id");
                if (formField1.getFieldTypeAttribute() != null) {
                    saveFormFieldSubsystem.setFieldTypeAttribute(FormFieldSubsystemFieldTypeAttributeEnum.get(formField1.getFieldTypeAttribute().getCode()));
                }
                if (formField1.getMethodType() != null) {
                    saveFormFieldSubsystem.setMethodType(FormFieldSubsystemMethodTypeEnum.get(formField1.getMethodType().getCode()));

                }
                saveFormFieldSubsystem.setRelatedId(formFieldSubsystemDTO.getRelatedId());

                baseService.save(saveFormFieldSubsystem);
            }
        }
        return R.success();
    }



}
